package com.dongnam.quanly.web.nghiepvu.muabanhang.hoadon;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.ChiTietDonHangController;
import com.dongnam.quanly.common.controller.ChiTietHoaDonController;
import com.dongnam.quanly.common.controller.DoiTacController;
import com.dongnam.quanly.common.controller.DonHangController;
import com.dongnam.quanly.common.controller.HoaDonController;
import com.dongnam.quanly.common.model.ChiTietDonHang;
import com.dongnam.quanly.common.model.ChiTietHoaDon;
import com.dongnam.quanly.common.model.DoiTac;
import com.dongnam.quanly.common.model.DonHang;
import com.dongnam.quanly.common.model.HoaDon;
import com.dongnam.quanly.common.model.enumtype.HinhThuc;
import com.dongnam.quanly.common.model.enumtype.LoaiHoaDon;
import com.dongnam.quanly.common.model.enumtype.TienTe;
import com.dongnam.quanly.common.model.enumtype.TrangThaiDonHang;
import com.dongnam.quanly.common.model.enumtype.TrangThaiHoaDon;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.LocaleMessages;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "HoaDonBean")
@SessionScoped
public class HoaDonBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(HoaDonBean.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;

	private StreamedContent file;

	private boolean checkEdit = false;
	private boolean checkEditCT = false;

	private HoaDon hoaDon;
	private HoaDon selectedHoaDon;
	private ChiTietHoaDon chiTiet;
	private ChiTietHoaDon selectedChiTiet;

	private List<HoaDon> hoaDonModel;
	private List<ChiTietHoaDon> chiTietModel;
	private List<ChiTietHoaDon> chiTietTempt;
	private List<DonHang> listDH;
	private List<DoiTac> listDT;
	private List<ChiTietDonHang> listCtDH;

	private HoaDonController hoaDonController;
	private DonHangController donHangController;
	private DoiTacController doiTacController;
	private ChiTietHoaDonController chiTietController;
	private ChiTietDonHangController ctDonHangController;

	private String loai;

	public HoaDonBean() {
		super();
		hoaDon = new HoaDon();
		hoaDonModel = new ArrayList<HoaDon>();
		chiTietModel = new ArrayList<ChiTietHoaDon>();
		listDH = new ArrayList<DonHang>();
		listDT = new ArrayList<DoiTac>();
		listCtDH = new ArrayList<ChiTietDonHang>();
		// TODO Auto-generated constructor stub
	}

	@PostConstruct
	public void init() {
		loai = "0";
		loadHoaDon();
	}

	public void reloadPage() {
		loadHoaDon();
		WebUtil.redirect("/pages/nghiepvu/muabanhang/hoadon.xhtml");
	}

	public void loadHoaDon() {
		try {
			hoaDonModel = getHoaDonController().findAll("updateDate", "Descending");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void handleFileUpload(FileUploadEvent event) {
		if ("0".equals(loai)) {
			fileUploadHD(event);
		} else if ("1".equals(loai)) {
			fileUploadCTHD(event);
		}
	}

	private void fileUploadHD(FileUploadEvent event) {
		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<HoaDon> list = new ArrayList<HoaDon>();
		int errorLine_1 = 0;
		int errorLine_2 = 0;
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines
			for (int i = 1; i < (sheet.getRows() - 1); i++) {
				for (int j = i + 1; j < sheet.getRows(); j++) {
					if (sheet.getCell(0, i).getContents().equals(sheet.getCell(0, j).getContents())) {
						errorLine_1 = i + 1;
						errorLine_2 = j + 1;
						throw new InvalidParameterException("Duplications");
					}
				}
			}
			for (int row = 1; row < sheet.getRows(); row++) {
				Cell cell_SoHoaDon = sheet.getCell(0, row);
				Cell cell_DoiTac = sheet.getCell(1, row);
				Cell cell_NgayHoaDon = sheet.getCell(2, row);
				Cell cell_NgayHoachToan = sheet.getCell(3, row);
				Cell cell_HTTT = sheet.getCell(4, row);
				Cell cell_TienTe = sheet.getCell(5, row);
				Cell cell_TyGia = sheet.getCell(6, row);
				Cell cell_SoDonHang = sheet.getCell(7, row);
				Cell cell_TongTien = sheet.getCell(8, row);
				Cell cell_TongTienUSD = sheet.getCell(9, row);
				Cell cell_LoaiHoaDon = sheet.getCell(10, row);
				Cell cell_TrangThai = sheet.getCell(11, row);

				HoaDon hd = new HoaDon();
				hd.setSoHoaDon(cell_SoHoaDon.getContents());
				hd.setDoiTac(cell_DoiTac.getContents());
				hd.setNgayHoaDon(DateFormatUtil.String2Date("MM/dd/yyyy", cell_NgayHoaDon.getContents()));
				hd.setNgayHachToan(DateFormatUtil.String2Date("MM/dd/yyyy", cell_NgayHoachToan.getContents()));
				hd.setHinhThucThanhToan(HinhThuc.getLabel(cell_HTTT.getContents()));
				hd.setTienTe(TienTe.valueOf(cell_TienTe.getContents()));
				hd.setTyGia(Double.parseDouble(cell_TyGia.getContents()));
				hd.setDonHang(cell_SoDonHang.getContents());
				hd.setTongTien(Double.parseDouble(cell_TongTien.getContents()));
				hd.setTongTien_USD(Double.parseDouble(cell_TongTienUSD.getContents()));
				hd.setLoaiHoaDon(LoaiHoaDon.getLabel(cell_LoaiHoaDon.getContents()));
				hd.setTrangThai(TrangThaiHoaDon.getLabel(cell_TrangThai.getContents()));
				list.add(hd);
			}
		} catch (InvalidParameterException e) {
			if (e.getMessage().equals("Duplications")) {
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString(
						"error_in_lines", errorLine_1, errorLine_2), null);
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
			rollback = true;
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
		if (!rollback) {
			getHoaDonController().batchSaveOrUpdate(list);
		}
		loadHoaDon();
	}

	private void fileUploadCTHD(FileUploadEvent event) {
		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<ChiTietHoaDon> list = new ArrayList<ChiTietHoaDon>();
		int errorLine_1 = 0;
		int errorLine_2 = 0;
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines
			for (int i = 1; i < (sheet.getRows() - 1); i++) {
				for (int j = i + 1; j < sheet.getRows(); j++) {
					if (sheet.getCell(0, i).getContents().equals(sheet.getCell(0, j).getContents())
							&& sheet.getCell(1, i).getContents().equals(sheet.getCell(1, j).getContents())) {
						errorLine_1 = i + 1;
						errorLine_2 = j + 1;
						throw new InvalidParameterException("Duplications");
					}
				}
			}
			for (int row = 1; row < sheet.getRows(); row++) {
				Cell cell_HoaDon = sheet.getCell(0, row);
				Cell cell_VTHH = sheet.getCell(1, row);
				Cell cell_nameVTHH = sheet.getCell(2, row);
				Cell cell_SoLuong = sheet.getCell(3, row);
				Cell cell_DonGia = sheet.getCell(4, row);
				Cell cell_DonGiaUSD = sheet.getCell(5, row);
				Cell cell_Thue = sheet.getCell(6, row);
				Cell cell_TongTien = sheet.getCell(7, row);
				Cell cell_TongTienUSD = sheet.getCell(8, row);

				ChiTietHoaDon ct = new ChiTietHoaDon();
				ct.setHoaDon(cell_HoaDon.getContents());
				ct.setMaVthh(cell_VTHH.getContents());
				ct.setTenVthh(cell_nameVTHH.getContents());
				ct.setSoLuong(Integer.parseInt(cell_SoLuong.getContents()));
				ct.setDonGiaMua(Double.parseDouble(cell_DonGia.getContents()));
				ct.setDonGiaMua_USD(Double.parseDouble(cell_DonGiaUSD.getContents()));
				ct.setThueGTGT(Double.parseDouble(cell_Thue.getContents()));
				ct.setThanhTien(Double.parseDouble(cell_TongTien.getContents()));
				ct.setThanhTien_USD(Double.parseDouble(cell_TongTienUSD.getContents()));
				list.add(ct);
			}
		} catch (InvalidParameterException e) {
			if (e.getMessage().equals("Duplications")) {
				FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString(
						"error_in_lines", errorLine_1, errorLine_2), null);
				FacesContext.getCurrentInstance().addMessage(null, msg);
			}
			rollback = true;
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
		if (!rollback) {
			getChiTietController().batchSaveOrUpdate(list);
		}
	}

	public void downloadFile() {
		if ("0".equals(loai)) {
			downloadHD();
		} else if ("1".equals(loai)) {
			downloadCTHD();
		}
	}

	private String checkString(String value) {
		if (null == value) {
			return " ";
		} else {
			return value;
		}
	}

	private String checkDate(Date value) {
		if (null == value) {
			return " ";
		} else {
			return value.toString();
		}
	}

	private void downloadHD() {
		File excelfile = new File("HOA_DON.xls");
		List<HoaDon> list = getHoaDonController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);
			sheet.setColumnView(10, 30);
			sheet.setColumnView(11, 30);

			sheet.addCell(new Label(0, 0, "Số Hóa Đơn", titleformat));
			sheet.addCell(new Label(1, 0, "Đối Tác", titleformat));
			sheet.addCell(new Label(2, 0, "Ngày Hóa Đơn", titleformat));
			sheet.addCell(new Label(3, 0, "Ngày Hoạch Toán", titleformat));
			sheet.addCell(new Label(4, 0, "Hình Thức Thanh Toán", titleformat));
			sheet.addCell(new Label(5, 0, "Tiền Tệ", titleformat));
			sheet.addCell(new Label(6, 0, "Tỷ Giá", titleformat));
			sheet.addCell(new Label(7, 0, "Đơn Hàng", titleformat));
			sheet.addCell(new Label(8, 0, "Tổng Tiền", titleformat));
			sheet.addCell(new Label(9, 0, "Tổng Tiền USD", titleformat));
			sheet.addCell(new Label(10, 0, "Loại Hóa Đơn", titleformat));
			sheet.addCell(new Label(11, 0, "Trạng Thái", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getSoHoaDon(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getDoiTac(), contentformat));
				sheet.addCell(new Label(2, i + 1, checkDate(list.get(i).getNgayHoaDon()), contentformat));
				sheet.addCell(new Label(3, i + 1, checkDate(list.get(i).getNgayHachToan()), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getHinhThucThanhToan().getValue(), contentformat));
				sheet.addCell(new Label(5, i + 1, String.valueOf(list.get(i).getTienTe()), contentformat));
				sheet.addCell(new Label(6, i + 1, checkString(String.valueOf(list.get(i).getTyGia())), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getDonHang(), contentformat));
				sheet.addCell(new Label(8, i + 1, checkString(String.valueOf(list.get(i).getTongTien())), contentformat));
				sheet.addCell(new Label(9, i + 1, checkString(String.valueOf(list.get(i).getTongTien_USD())),
						contentformat));
				sheet.addCell(new Label(10, i + 1, String.valueOf(list.get(i).getLoaiHoaDon()), contentformat));
				sheet.addCell(new Label(11, i + 1, list.get(i).getTrangThai().getValue(), contentformat));
			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "HOA_DON.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	private void downloadCTHD() {
		File excelfile = new File("CHI_TIET_HOA_DON.xls");
		List<ChiTietHoaDon> list = getChiTietController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);

			sheet.addCell(new Label(0, 0, "Số Hóa Đơn", titleformat));
			sheet.addCell(new Label(1, 0, "Mã Vật Tư Hàng Hóa", titleformat));
			sheet.addCell(new Label(2, 0, "Tên Vật Tư", titleformat));
			sheet.addCell(new Label(3, 0, "Số Lượng", titleformat));
			sheet.addCell(new Label(4, 0, "Đơn Giá Mua", titleformat));
			sheet.addCell(new Label(5, 0, "Đơn Giá Mua USD", titleformat));
			sheet.addCell(new Label(6, 0, "Thuế Giá Trị Gia Tăng", titleformat));
			sheet.addCell(new Label(7, 0, "Thành Tiền", titleformat));
			sheet.addCell(new Label(8, 0, "Thành Tiền USD", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getHoaDon(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getMaVthh(), contentformat));
				sheet.addCell(new Label(2, i + 1, checkString(list.get(i).getTenVthh()), contentformat));
				sheet.addCell(new Label(3, i + 1, String.valueOf(list.get(i).getSoLuong()), contentformat));
				sheet.addCell(new Label(4, i + 1, String.valueOf(list.get(i).getDonGiaMua()), contentformat));
				sheet.addCell(new Label(5, i + 1, String.valueOf(list.get(i).getDonGiaMua_USD()), contentformat));
				sheet.addCell(new Label(6, i + 1, String.valueOf(list.get(i).getThueGTGT()), contentformat));
				sheet.addCell(new Label(7, i + 1, String.valueOf(list.get(i).getThanhTien()), contentformat));
				sheet.addCell(new Label(8, i + 1, String.valueOf(list.get(i).getThanhTien_USD()), contentformat));
			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv",
					"CHI_TIET_HOA_DON.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void resetFormAdd() {
		hoaDon = new HoaDon();
	}

	public void notifyAdd() {
		FacesContext facescontext = FacesContext.getCurrentInstance();
		RequestContext requestcontext = RequestContext.getCurrentInstance();
		listDoiTac();

		if (listDT.size() == 0) {
			facescontext.addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("invalid_loadDT"), null));
			requestcontext.addCallbackParam("opSuccess", false);
			return;
		}
		if (null != listDH) {
			listDH.clear();
		}
		checkEdit = false;
		resetFormAdd();
		if (chiTietModel != null) {
			chiTietModel = new ArrayList<ChiTietHoaDon>();
		}
		chiTietModel.clear();
		requestcontext.addCallbackParam("opSuccess", true);
	}

	public void notifyEdit(HoaDon hoaDon) {
		FacesContext facescontext = FacesContext.getCurrentInstance();
		RequestContext requestcontext = RequestContext.getCurrentInstance();
		listDoiTac();
		if (listDT.size() == 0) {
			facescontext.addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("invalid_loadDT"), null));
			requestcontext.addCallbackParam("opSuccess", false);
			return;
		}
		checkEdit = true;
		this.hoaDon = hoaDon;
		loadChiTietHoaDon(this.hoaDon.getSoHoaDon());
		if (chiTietModel != null) {
			if (chiTietTempt == null) {
				chiTietTempt = new ArrayList<ChiTietHoaDon>();
			}

			for (int i = 0; i < chiTietModel.size(); i++) {
				ChiTietHoaDon ct = new ChiTietHoaDon(this.chiTietModel.get(i));
				chiTietTempt.add(ct);
			}

		}
		listDH = getDonHangController().getListDonHang(hoaDon.getDoiTac(), TrangThaiDonHang.DANG_THUC_HIEN);
	}

	public void removeHoaDon() {
		FacesContext facescontext = FacesContext.getCurrentInstance();
		if (this.selectedHoaDon != null) {
			try {
				getHoaDonController().makeTransient(this.selectedHoaDon);
				facescontext.addMessage(null, new FacesMessage(LocaleMessages.getString("general_delete_success")));
			} catch (Exception e) {
				e.printStackTrace();
				facescontext.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR,
								LocaleMessages.getString("general_delete_failed"), null));
			}

			loadHoaDon();
		}

	}

	public void save() {
		FacesContext facescontext = FacesContext.getCurrentInstance();
		RequestContext requestcontext = RequestContext.getCurrentInstance();
		try {
			if (!checkEdit) {
				for (int i = 0; i < chiTietModel.size(); i++) {
					chiTietModel.get(i).setHoaDon(hoaDon.getSoHoaDon());
				}
				if (getHoaDonController().checkHd(this.hoaDon.getSoHoaDon())) {
					facescontext.addMessage(null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("hoaDon") + " "
									+ LocaleMessages.getString("record_existed"), null));
					requestcontext.addCallbackParam("opSuccess", false);
					return;
				}
			}

			if (!(null == hoaDon.getNgayHoaDon() && null == hoaDon.getNgayHachToan())) {
				if (null == hoaDon.getNgayHoaDon() || null == hoaDon.getNgayHachToan()) {
					facescontext.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages
									.getString("invalid_date_hoadon"), null));
					requestcontext.addCallbackParam("opSuccess", false);
					return;
				}
				if (!hoaDon.getNgayHoaDon().after(hoaDon.getNgayHachToan())) {
					facescontext.addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages
									.getString("invalid_date_hoadon"), null));
					requestcontext.addCallbackParam("opSuccess", false);
					return;
				}
			}

			if (checkEdit) {
				getChiTietController().batchDelete(chiTietTempt);
			}

			getHoaDonController().makePersistent(hoaDon);
			facescontext.addMessage(
					null,
					new FacesMessage(LocaleMessages.getString(checkEdit ? "general_edit_success"
							: "general_add_success")));

			getChiTietController().batchPersist(chiTietModel);
			requestcontext.addCallbackParam("opSuccess", true);
		} catch (Exception e) {
			e.printStackTrace();
			facescontext.addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages
							.getString(checkEdit ? "general_edit_success" : "general_add_fail"), null));
		}
		loadHoaDon();
	}

	private void loadChiTietHoaDon(String hoadon) {
		try {
			chiTietModel = getChiTietController().getListCt(hoadon);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void notifyAddChiTiet() {
		checkEditCT = false;
		chiTiet = new ChiTietHoaDon();

		FacesContext facescontext = FacesContext.getCurrentInstance();
		RequestContext requestcontext = RequestContext.getCurrentInstance();
		if (!checkEdit) {
			if (getHoaDonController().checkHd(this.hoaDon.getSoHoaDon())) {
				facescontext.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("hoaDon") + " "
								+ LocaleMessages.getString("record_existed"), null));
				requestcontext.addCallbackParam("opSuccess", false);
				return;
			}
		}

		listCtDH = getCtDonHangController().getListCtdh(this.hoaDon.getDonHang());
		if (listCtDH.isEmpty()) {
			facescontext.addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("invalid_ctdonhang"), null));
			requestcontext.addCallbackParam("opSuccess", false);
			return;
		}

		chiTiet.setHoaDon(this.hoaDon.getSoHoaDon());
		requestcontext.addCallbackParam("opSuccess", true);
	}

	public void removeChiTiet(String maVthh) {
		for (int i = 0; i < chiTietModel.size(); i++) {
			if (chiTietModel.get(i).getMaVthh().equals(maVthh)) {
				chiTietModel.remove(i);
				return;
			}
		}
	}

	public void saveChiTiet() {
		FacesContext facescontext = FacesContext.getCurrentInstance();
		RequestContext requestcontext = RequestContext.getCurrentInstance();

		for (int i = 0; i < chiTietModel.size(); i++) {
			chiTietModel.get(i).setHoaDon(chiTiet.getHoaDon());
		}

		for (int i = 0; i < chiTietModel.size(); i++) {
			if (chiTietModel.get(i).getMaVthh().equals(chiTiet.getMaVthh())) {
				facescontext.addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleMessages.getString("mavthh") + " "
								+ LocaleMessages.getString("record_existed"), null));
				return;
			}
		}
		chiTietModel.add(chiTiet);
		requestcontext.addCallbackParam("opSuccess", true);
	}

	/**
	 * Lấy list đơn hàng
	 */
	public void listDonHang() {
		if (hoaDon.getDoiTac() == null || hoaDon.getDoiTac() == "") {
			listDH.clear();
		} else {
			listDH = getDonHangController().getListDonHang(hoaDon.getDoiTac(), TrangThaiDonHang.DANG_THUC_HIEN);
		}
	}

	/**
	 * Lấy list đối tác
	 */
	public void listDoiTac() {
		listDT = getDoiTacController().findAll();
	}

	/**
	 * Lấy list enum hình thức thanh toán
	 */
	public HinhThuc[] getHinhThuc() {
		return HinhThuc.values();
	}

	/**
	 * Lấy list enum tiền tệ
	 */
	public TienTe[] getTienTe() {
		return TienTe.values();
	}

	/**
	 * Lấy list enum loại hóa đơn
	 */
	public LoaiHoaDon[] getLoaiHoaDon() {
		return LoaiHoaDon.values();
	}

	/**
	 * Lấy list enum trạng thái hóa đơn
	 */
	public TrangThaiHoaDon[] getTrangThai() {
		return TrangThaiHoaDon.values();
	}

	/**
	 * Get set function
	 */
	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public boolean isCheckEdit() {
		return checkEdit;
	}

	public void setCheckEdit(boolean checkEdit) {
		this.checkEdit = checkEdit;
	}

	public HoaDon getHoaDon() {
		return hoaDon;
	}

	public void setHoaDon(HoaDon hoaDon) {
		this.hoaDon = hoaDon;
	}

	public HoaDon getSelectedHoaDon() {
		return selectedHoaDon;
	}

	public void setSelectedHoaDon(HoaDon selectedHoaDon) {
		this.selectedHoaDon = selectedHoaDon;
	}

	public HoaDonController getHoaDonController() {
		if (this.hoaDonController == null) {
			this.hoaDonController = new HoaDonController();
		}
		return this.hoaDonController;
	}

	public void setHoaDonController(HoaDonController hoaDonController) {
		this.hoaDonController = hoaDonController;
	}

	public List<HoaDon> getHoaDonModel() {
		return hoaDonModel;
	}

	public void setHoaDonModel(List<HoaDon> hoaDonModel) {
		this.hoaDonModel = hoaDonModel;
	}

	public List<ChiTietHoaDon> getChiTietModel() {
		return chiTietModel;
	}

	public void setChiTietModel(List<ChiTietHoaDon> chiTietModel) {
		this.chiTietModel = chiTietModel;
	}

	public DonHangController getDonHangController() {
		if (donHangController == null) {
			donHangController = new DonHangController();
		}
		return donHangController;
	}

	public DoiTacController getDoiTacController() {
		if (doiTacController == null) {
			doiTacController = new DoiTacController();
		}
		return doiTacController;
	}

	public List<DonHang> getListDH() {
		return listDH;
	}

	public void setListDH(List<DonHang> listDH) {
		this.listDH = listDH;
	}

	public List<DoiTac> getListDT() {
		return listDT;
	}

	public void setListDT(List<DoiTac> listDT) {
		this.listDT = listDT;
	}

	public ChiTietHoaDon getChiTiet() {
		return chiTiet;
	}

	public void setChiTiet(ChiTietHoaDon chiTiet) {
		this.chiTiet = chiTiet;
	}

	public ChiTietHoaDonController getChiTietController() {
		if (chiTietController == null)
			chiTietController = new ChiTietHoaDonController();
		return chiTietController;
	}

	public ChiTietHoaDon getSelectedChiTiet() {
		return selectedChiTiet;
	}

	public void setSelectedChiTiet(ChiTietHoaDon selectedChiTiet) {
		this.selectedChiTiet = selectedChiTiet;
	}

	public boolean isCheckEditCT() {
		return checkEditCT;
	}

	public void setCheckEditCT(boolean checkEditCT) {
		this.checkEditCT = checkEditCT;
	}

	public String getLoai() {
		return loai;
	}

	public void setLoai(String loai) {
		this.loai = loai;
	}

	public ChiTietDonHangController getCtDonHangController() {
		if (ctDonHangController == null) {
			ctDonHangController = new ChiTietDonHangController();
		}
		return ctDonHangController;
	}

	public List<ChiTietDonHang> getListCtDH() {
		return listCtDH;
	}

	public void setListCtDH(List<ChiTietDonHang> listCtDH) {
		this.listCtDH = listCtDH;
	}

	public List<ChiTietHoaDon> getChiTietTempt() {
		return chiTietTempt;
	}

	public void setChiTietTempt(List<ChiTietHoaDon> chiTietTempt) {
		this.chiTietTempt = chiTietTempt;
	}

}
